#pragma once

#include <iostream>
#include <sys/socket.h>
#include <cstring>
#include <cstdint>
#include <arpa/inet.h>
#include <string>
#include "log.hpp"

using namespace Logspace;

const std::string defaultip_ = "0.0.0.0";
enum SockErr
{
    SOCKET_Err,
    BIND_Err,
};

class Sock
{
public:
    Sock(uint16_t port)
        : port_(port),
          listensockfd_(-1)
    {
    }
    void Socket()
    {
        listensockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (listensockfd_ < 0)
        {
            Log(Fatal) << "socket fail";
            exit(SOCKET_Err);
        }
        Log(Info) << "socket sucess";
    }
    void Bind()
    {
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(port_);
        inet_pton(AF_INET, defaultip_.c_str(), &server.sin_addr);
        if (bind(listensockfd_, (struct sockaddr *)&server, sizeof(server)) < 0)
        {
            Log(Fatal) << "bind fail";
            exit(BIND_Err);
        }
        Log(Info) << "bind sucess";
    }
    void Listen()
    {
        if (listen(listensockfd_, 10) < 0)
        {
            Log(Warning) << "listen fail";
        }
        Log(Info) << "listen sucess";
    }
    int Accept()
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int fd = accept(listensockfd_ , (sockaddr*)&client , &len);
        if(fd < 0)
        {
            Log(Warning) << "accept fail";
        }
        return fd;
    }
    int Accept(std::string& ip , uint16_t& port)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int fd = accept(listensockfd_ , (sockaddr*)&client , &len);
        if(fd < 0)
        {
            Log(Warning) << "accept fail";
        }

        port = ntohs(client.sin_port);
        char bufferip[64];
        inet_ntop(AF_INET , &client.sin_addr , bufferip , sizeof(bufferip) - 1);
        ip = bufferip;

        return fd;
    }
    int Get_fd()
    {
        return listensockfd_;
    }
    ~Sock()
    {
        close(listensockfd_);
    }

private:
    uint16_t port_;
    int listensockfd_;
};